
#import "APDataManager.h"
#import "APErrorCatchManager.h"
#import "APLoginViewController.h"
#import "NSString+Category.h"
#import "APLoginViewController.h"
#import "NSMutableDictionary+NullValue.h"
#import "APUUIDManager.h"
#import "APLoginManager.h"
#ifdef DEBUG
#define TIMEOUT_INTERVAL 30
#else
#define TIMEOUT_INTERVAL 30
#endif

@implementation APDataManager
+ (DMNetWorkStatus)netWorkStatusChanged:(DMNetworkReachabilityStatusBlock)notWorkStatus
{
    __block  DMNetWorkStatus NetStatus = DMNetWorkStatusUnknown;
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NetStatus = DMNetWorkStatusUnknown;
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NetStatus = DMNetWorkStatusNotReachable;
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NetStatus = DMNetWorkStatusReachableViaWiFi;
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NetStatus = DMNetWorkStatusReachableViaWWAN;
                break;
            default:
                NetStatus = DMNetWorkStatusUnknown;
                break;
        }
        if (notWorkStatus) {
            notWorkStatus(NetStatus);
        }
    }];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    return NetStatus;
}

+ (void)requestOriginalData:(NSString *)urlString parameters:(NSDictionary *)parameters result:(void (^)(id responseObject))result  failBlock:(void (^)(NSString *errorMessage))failBlock{
        NSString *urlStr = [urlString urlEncode];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [APDataManager addHttpHeaderFields:manager];
        manager.securityPolicy = [self _getsecurityPolicy];
        [manager POST:urlStr parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [APDataManager showLoginView:responseObject];
            if (result) {
                 result (responseObject);
             }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failBlock) {
                NSError *localError = [[APErrorCatchManager manager] getError:error];
                NSString *message = localError.userInfo[@"message"];
                failBlock(message);
            }
        }];
}
+ (void)requestData:(NSString *)urlString parameters:(NSDictionary *)parameters result:(void (^)(NSDictionary *res))result  failBlock:(void (^)(NSString *errorMsg))failBlock{
    NSString *urlStr = [urlString urlEncode];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    AFJSONResponseSerializer *response =  [AFJSONResponseSerializer serializer];
    response.removesKeysWithNullValues = YES;
    manager.responseSerializer = response;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json", @"text/javascript",@"text/plain", nil];
    [APDataManager addHttpHeaderFields:manager];
    manager.securityPolicy = [self _getsecurityPolicy];
    [manager POST:urlStr parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [APDataManager showLoginView:responseObject];
        NSDictionary *jsonData = responseObject;
        if (jsonData && [jsonData isKindOfClass:[NSDictionary class]]) {
            if ([APDataManager isRequestSuccess:jsonData]) {
                if (result) {
                    result (jsonData);
                }
            }else{
                NSString *message = [jsonData[@"message"] description];
                if (failBlock) {
                    failBlock(message);
                }
            }
        }else{
            if (failBlock) {
                failBlock(@"data exception");
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failBlock) {
            NSError *localError = [[APErrorCatchManager manager] getError:error];
            NSString *message = localError.userInfo[@"message"];
            failBlock(message);
        }
    }];

}

+ (void)postWithUrlString:(NSString *)urlString parameters:(NSDictionary *)parameters result:(void (^)(NSDictionary *))result failBlock:(void (^)(NSString *))failBlock{
    NSString *urlStr = [urlString urlEncode];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 20;
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    AFJSONResponseSerializer *response =  [AFJSONResponseSerializer serializer];
    response.removesKeysWithNullValues = YES;
    manager.responseSerializer = response;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json", @"text/javascript",@"text/plain", nil];
    [APDataManager addHttpHeaderFields:manager];
    manager.securityPolicy = [self _getsecurityPolicy];
    [manager POST:urlStr parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *jsonData = responseObject;
        LYLog(@"========%@===%@",responseObject,[responseObject[@"message"] description]);
        if (jsonData && [jsonData isKindOfClass:[NSDictionary class]]) {
            if (result) {
                result (jsonData);
            }
        }else{
            if (failBlock) {
                failBlock(@"data error");
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failBlock) {
            NSError *localError = [[APErrorCatchManager manager] getError:error];
            NSString *message = localError.userInfo[@"message"];
            failBlock(message);
        }
    }];
}

+ (void)postJsonWithUrlString:(NSString *)urlString timeoutInterval:(NSTimeInterval)timeout parameters:(id)parameters result:(void (^)(NSDictionary *))result failBlock:(void (^)(NSString *))failBlock{
    NSString *urlStr = [urlString urlEncode];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    AFJSONResponseSerializer *response =  [AFJSONResponseSerializer serializer];
    response.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json", @"text/javascript",@"text/plain", nil];
//    response.removesKeysWithNullValues = YES;
    manager.responseSerializer = response;
    if (timeout != 0) {
        manager.requestSerializer.timeoutInterval = timeout;
    }else{
        manager.requestSerializer.timeoutInterval = TIMEOUT_INTERVAL;
    }
    [APDataManager addHttpHeaderFields:manager];
    manager.securityPolicy = [self _getsecurityPolicy];
    LYLog(@"--%@",parameters);

    [manager POST:urlStr parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        LYLog(@"--%@----%@",urlString,responseObject);
        NSDictionary *jsonData = responseObject;
        if (jsonData && [jsonData isKindOfClass:[NSDictionary class]]) {
            if ([APDataManager isRequestSuccess:jsonData]) {
                if (result) {
                    result (jsonData);
                }
            }else{
                NSString *message = [jsonData[@"msg"] description];
                if (failBlock) {
                    failBlock(message);
                }
            }
        }else{
            if (failBlock) {
                failBlock(@"data error");
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        LYLog(@"%@",error);
        if (failBlock) {
            NSError *localError = [[APErrorCatchManager manager] getError:error];
            NSString *message = localError.userInfo[@"message"];
            failBlock(message);
        }
    }];
}

+ (void)getDataWithUrlString:(NSString *)urlString result:(void (^)(NSDictionary *))result failBlock:(void (^)(NSString *))failBlock{
    NSString *urlStr = [urlString urlEncode];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json", @"text/javascript",@"text/plain", nil];
    AFJSONResponseSerializer *response =  [AFJSONResponseSerializer serializer];
    response.removesKeysWithNullValues = YES;
    manager.responseSerializer = response;
    manager.requestSerializer.timeoutInterval = TIMEOUT_INTERVAL;
    [manager.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
    [APDataManager addHttpHeaderFields:manager];
    manager.securityPolicy = [self _getsecurityPolicy];
    NSURLSessionTask *task = [manager GET:urlStr parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *jsonData = responseObject;
        if (jsonData && [jsonData isKindOfClass:[NSDictionary class]]) {
            [APDataManager showLoginView:responseObject];
            if ([APDataManager isRequestSuccess:jsonData]) {
                if (result) {
                    result (jsonData);
                }
            }else{
                NSString *message = [jsonData[@"msg"] description];
                if (failBlock) {
                    failBlock(message);
                }
            }
        }else{
            if (failBlock) {
                failBlock(@"data exception");
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            if (failBlock) {
                NSError *localError = [[APErrorCatchManager manager] getError:error];
                NSString *message = localError.userInfo[@"message"];
                if (failBlock) {
                    failBlock(message);
                }
            }
        }
    }];
    [task resume];
}

+ (void)getDataNoProcessWithUrlString:(NSString *)urlString jsonObject:(void (^)(NSDictionary *))result fail:(void (^)(NSError *))fail{
    NSString *urlStr = [urlString urlEncode];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json", @"text/javascript",@"text/plain", nil];
    AFJSONResponseSerializer *response =  [AFJSONResponseSerializer serializer];
    response.removesKeysWithNullValues = YES;
    manager.responseSerializer = response;
    manager.requestSerializer.timeoutInterval = TIMEOUT_INTERVAL;
    [manager.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
    [APDataManager addHttpHeaderFields:manager];
    manager.securityPolicy = [self _getsecurityPolicy];
    NSURLSessionTask *task = [manager GET:urlStr parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (result) {
            result(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (fail) {
            fail(error);
        }
    }];
    [task resume];
}

+ (void)uploadImagesWithUrl:(NSString *)url policy:(APOSSPolicyModel *)ossModel image:(UIImage *)image progress:(void (^)(NSProgress * _Nonnull))progress resultBlock:(void (^)(NSString * _Nonnull))resultBlock failBlock:(void (^)(NSString * _Nonnull))failBlock{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setTimeoutInterval:60];
    manager.securityPolicy = [self _getsecurityPolicy];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setNullObject:ossModel.accessKeyId forKey:@"ossaccessKeyId"];
    [parameters setNullObject:ossModel.policy forKey:@"policy"];
    [parameters setNullObject:ossModel.signature forKey:@"signature"];
    [parameters setNullObject:ossModel.callback forKey:@"callback"];
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval time= [date timeIntervalSince1970]*1000;// *1000 是精确到毫秒，不乘就是精确到秒
    NSString *imageName = [NSString stringWithFormat:@"%.0f.jpg", time];
    NSString *key = [NSString stringWithFormat:@"%@/%@",ossModel.dir,imageName];
    [parameters setNullObject:key forKey:@"key"];
    [manager POST:url parameters:parameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *imageDa = UIImageJPEGRepresentation(image, 1);
        [formData appendPartWithFileData:imageDa name:@"file" fileName:imageName mimeType:@"image/jpeg"];
            
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (progress) {
                progress(uploadProgress);
            }
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError *error = nil;
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        if (!error) {
            if ([APDataManager isRequestSuccess:json]) {
                if (resultBlock) {
                    resultBlock([json[@"data"][@"filename"] description]);
                }
            }else{
                if (failBlock) {
                    failBlock(json[@"msg"]);
                }
            }
        }else{
            if (failBlock) {
                failBlock(@"data exception");
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error && failBlock) {
            NSError *localError = [[APErrorCatchManager manager] getError:error];
            failBlock(localError.userInfo[@"message"]);
        }
    }];
}

+ (void)uploadImagesWithUrl:(NSString *)url policy:(APOSSPolicyModel *)ossModel imageUrl:(NSString *)urlString progress:(void (^)(NSProgress * _Nonnull))progress resultBlock:(void (^)(NSArray<APImageModel *> * _Nonnull))resultBlock failBlock:(void (^)(NSString * _Nonnull))failBlock{
    
}

void(^appendImageFormData) (UIImage * ,NSString *, id<AFMultipartFormData>) = ^(UIImage *image ,NSString *name, id<AFMultipartFormData>  _Nonnull formData){
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval time= [date timeIntervalSince1970]*1000;// *1000 是精确到毫秒，不乘就是精确到秒
    NSString *imageName = [NSString stringWithFormat:@"%.0f.jpg", time];
    NSData *imageDa = UIImageJPEGRepresentation(image, 1);
    [formData appendPartWithFileData:imageDa name:name fileName:imageName mimeType:@"image/jpeg"];
};

void(^appendImagesData) (UIImage * ,NSString *, id<AFMultipartFormData>) = ^(UIImage *image ,NSString *name, id<AFMultipartFormData>  _Nonnull formData){
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval time= [date timeIntervalSince1970]*1000;
    NSString *imageName = [NSString stringWithFormat:@"%.0f.jpg", time];
    NSData *imageDa = UIImageJPEGRepresentation(image, 1);
    NSString *str = name == nil ? imageName : name;
    [formData appendPartWithFileData:imageDa name:str fileName:imageName mimeType:@"image/jpeg"];

};

void(^appendImageFileURL) (NSURL * ,NSString *, id<AFMultipartFormData>) = ^(NSURL *fileURL ,NSString *name, id<AFMultipartFormData>  _Nonnull formData){
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval time= [date timeIntervalSince1970]*1000;
    NSString *nameStr = [NSString stringWithFormat:@"%.0f", time];
    NSError *error = nil;
    if (fileURL){
        [formData appendPartWithFileURL:fileURL name:nameStr error:&error];
        NSLog(@"====error====%@",error);
    }
};



+ (void)showLoginView:(id)responseObject{
//    if (!responseObject) {
//        return;
//    }
//    NSDictionary *jsonData = responseObject;
//    NSError *error = nil;
//    if ([responseObject isKindOfClass:[NSData class]]) {
//        jsonData = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
//    }
//    APLoginViewController *loginVC = [[APLoginViewController alloc] init];
//    [[[UIApplication sharedApplication] keyWindow].rootViewController presentViewController:loginVC animated:YES completion:nil];
}


+ (void)addHttpHeaderFields:(AFHTTPSessionManager *)manager{
//    manager.session.configuration.connectionProxyDictionary = @{};
    bool isLogin = [[APLoginManager shareInstance] isLogin];
    if (isLogin) {
        APUserModel *userModel = [[APLoginManager shareInstance] userInfo];
        NSString *token = [[APLoginManager shareInstance] token];
        [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer%@",token] forHTTPHeaderField:@"Authorization"];
        [manager.requestSerializer setValue:[userModel.userId description] forHTTPHeaderField:@"userId"];
    }
    [manager.requestSerializer setValue:[APUUIDManager dm_getUUID] forHTTPHeaderField:@"device-id"];
    [manager.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"platform"];
    [manager.requestSerializer setValue:[UIDevice currentDevice].model forHTTPHeaderField:@"model"];
    [manager.requestSerializer setValue:[NSBundle mainBundle].bundleIdentifier forHTTPHeaderField:@"pkg"];
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    [manager.requestSerializer setValue:app_Version forHTTPHeaderField:@"ver"];
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"%d",1] forHTTPHeaderField:@"kst"];
    NSString *lan = [NSLocale currentLocale].languageCode;
    if (lan) {
        [manager.requestSerializer setValue:lan forHTTPHeaderField:@"sys_lan"];
        [manager.requestSerializer setValue:lan forHTTPHeaderField:@"lang"];
    }
    
    LYLog(@"===%@",manager.requestSerializer.HTTPRequestHeaders);
}


//判断请求是否成功
+ (BOOL)isRequestSuccess:(NSDictionary *)responseObject{
    return [responseObject[@"success"] intValue] == 1;
}

+ (AFSecurityPolicy *)_getsecurityPolicy{
//    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"www.mysite.com" ofType:@"cer"];
//    NSData *certData =[NSData dataWithContentsOfFile:cerPath];
//    NSSet *certSet = [[NSSet alloc] initWithObjects:certData, nil];
    //    [securityPolicy setPinnedCertificates:certSet];
    // 是否允许,NO-- 不允许无效的证书
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    [securityPolicy setAllowInvalidCertificates:YES];
    securityPolicy.validatesDomainName = NO;
    return securityPolicy;
}



@end
